package com.drawu.drawuspring.utils;

import com.alibaba.fastjson.JSONObject;
import com.drawu.drawuspring.domain.DTO.PostDTO;
import com.drawu.drawuspring.domain.Result;
import com.drawu.drawuspring.domain.po.Posts;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

public class Coze {
    public static final String spaceId = "7419142395348303922"; // Coze空间ID
    public static final String workflowId = "7485368102395609151"; // Coze工作流
//    public static final String commentWorkflowId= "7486059684798218251"; // Coze工作流
    public static final String botId = "7419130443436048394"; // Coze机器人ID
    private static final Logger log = LoggerFactory.getLogger(Coze.class);

    public static String createConversation() throws Exception {
        String CozeURL = "https://api.coze.cn/v1/conversation/create";
        HttpPost httpPost = new HttpPost(CozeURL);
        // 设置头字段
        httpPost.setHeader("Authorization", "Bearer " + JWTSignature.getToken());
        httpPost.addHeader("content-type", "application/json");
        // 发送请求
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httpPost);
        // 处理返回结果
        String resCont = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        System.out.println("\n################# 创建会话resCont #################"+resCont);
        JSONObject res = JSONObject.parseObject(resCont);
        String conversationId = res.getJSONObject("data").getString("id");

        return conversationId;
    }

    public static String createChat(String content, String conversationId) throws Exception {
        String CozeURL = "https://api.coze.cn/v3/chat" + "?conversation_id=" + conversationId;

        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(CozeURL);
        // 设置头字段
        httpPost.setHeader("Authorization", "Bearer " + JWTSignature.getToken());
        httpPost.addHeader("content-type", "application/json");

        // 设置内容信息
        JSONObject json = new JSONObject();
        json.put("bot_id", botId); // 机器人id
        json.put("user_id", "1234567"); // 用户id
        json.put("stream", false); // 流式传输
        json.put("auto_save_history", true); // 自动保存历史

        JSONObject additional_message = new JSONObject();
        additional_message.put("role", "user"); // 用户id
        additional_message.put("content", content); // 消息内容
        additional_message.put("content_type", "text"); // 消息类型
        json.put("additional_message", additional_message);

        StringEntity params = new StringEntity(json.toString());
        httpPost.setEntity(params);

        // 发送请求
        HttpResponse response = httpClient.execute(httpPost);

        // 处理返回结果
        String resCont = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        JSONObject res = JSONObject.parseObject(resCont);
//        System.out.println("\n################# 创建消息resCont #################"+resCont);
        String chatId = res.getJSONObject("data").getString("id");

        return chatId;
    }

    public static String retrieveChat(String chatId, String conversationId) throws Exception {
        String CozeURL = "https://api.coze.cn/v3/chat/retrieve" + "?chat_id=" + chatId + "&conversation_id=" + conversationId;
        System.out.println(CozeURL);
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(CozeURL);
        // 设置头字段
        httpGet.setHeader("Authorization", "Bearer " + JWTSignature.getToken());
        httpGet.addHeader("Content-Type", "application/json");

//        // 发送请求
//        HttpResponse response = httpClient.execute(httpGet);
//
//        // 处理返回结果
//        String resCont = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
//        JSONObject res = JSONObject.parseObject(resCont);
//        System.out.println("\n################# 查看消息resCont #################"+resCont);
//        return resCont;
        return null;
    }
    public static JSONObject runWorkflow1(String resume, String chatworkflowId) throws Exception {
        String CozeURL = "https://api.coze.cn/v1/workflow/run"; // 非流式传输
//         String CozeURL = "https://api.coze.cn/v1/workflow/stream_run"; // 流式传输
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(CozeURL);
        // 设置头字段
        httpPost.setHeader("Authorization", "Bearer " + JWTSignature.getToken());
        httpPost.addHeader("content-type", "application/json; charset=UTF-8");
// 需要先对resume进行Base64编码
//        String encodedResume = Base64.getEncoder().encodeToString(resume.getBytes(StandardCharsets.UTF_8));
        // 设置内容信息
        JSONObject json = new JSONObject();
        json.put("workflow_id", chatworkflowId); // 工作流id
        Map<String,Object> parameters = new HashMap<>();
        parameters.put("input", resume); // 输入
        json.put("parameters", parameters);
        StringEntity params = new StringEntity(json.toString(),"UTF-8");

        System.out.println(params);
        System.out.println(json.toString());
        httpPost.setEntity(params);
        // 发送请求
        HttpResponse response = httpClient.execute(httpPost);
        // 处理返回结果
        String resCont = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        JSONObject res = JSONObject.parseObject(JSONObject.parseObject(resCont).getString("data"));
        System.out.println("\n################# 运行工作流resCont #################"+res);
        return res;
    }

    public static JSONObject runWorkflow(PostDTO postDTO) throws Exception {
        String CozeURL = "https://api.coze.cn/v1/workflow/run"; // 非流式传输
//         String CozeURL = "https://api.coze.cn/v1/workflow/stream_run"; // 流式传输
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(CozeURL);
        // 设置头字段
        httpPost.setHeader("Authorization", "Bearer " + JWTSignature.getToken());
        httpPost.addHeader("content-type", "application/json; charset=UTF-8");
// 需要先对resume进行Base64编码
//        String encodedResume = Base64.getEncoder().encodeToString(resume.getBytes(StandardCharsets.UTF_8));
        // 设置内容信息
        JSONObject json = new JSONObject();
        json.put("workflow_id", workflowId); // 工作流id
        Map<String,Object> parameters = new HashMap<>();
//        parameters.put("BOT_USER_INPUT", postDTO.getContent()); // 输入
        Map<String,Object> input = new HashMap<>();
        input.put("title", postDTO.getTitle());
        input.put("content", postDTO.getContent());
        input.put("urls", postDTO.getImages());
        parameters.put("input", input);
        json.put("parameters", parameters);
        StringEntity params = new StringEntity(json.toString(),"UTF-8");

        System.out.println(params);
        System.out.println(json.toString());
        httpPost.setEntity(params);
        // 发送请求
        HttpResponse response = httpClient.execute(httpPost);
        // 处理返回结果
        String resCont = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        JSONObject res = JSONObject.parseObject(JSONObject.parseObject(resCont).getString("data"));
        System.out.println("\n################# 运行工作流resCont #################"+res);
        return res;
    }

    public static JSONObject runWorkflowCommon(String workflowId, Map<String,Object> input) throws Exception {
        String CozeURL = "https://api.coze.cn/v1/workflow/run"; // 非流式传输
//         String CozeURL = "https://api.coze.cn/v1/workflow/stream_run"; // 流式传输
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(CozeURL);
        // 设置头字段
        httpPost.setHeader("Authorization", "Bearer " + JWTSignature.getToken());
        httpPost.addHeader("content-type", "application/json; charset=UTF-8");
        // 设置内容信息
        JSONObject json = new JSONObject();
        json.put("workflow_id", workflowId); // 工作流id
        Map<String,Object> parameters = new HashMap<>();
        parameters.put("input", input);
        json.put("parameters", parameters);
        StringEntity params = new StringEntity(json.toString(),"UTF-8");

        System.out.println(params);
        System.out.println(json.toString());
        httpPost.setEntity(params);
        // 发送请求
        HttpResponse response = httpClient.execute(httpPost);
        // 处理返回结果
        String resCont = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        JSONObject res = JSONObject.parseObject(JSONObject.parseObject(resCont).getString("data"));
        System.out.println("\n################# 运行工作流resCont #################"+res);
        return res;
    }

    // 流式返回
    public static <T> ResponseBodyEmitter runWorkflowStream(String workflowId, T input) throws Exception {
        // 延长超时时间
        SseEmitter emitter = new SseEmitter(120_000L);

        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("https://api.coze.cn/v1/workflow/stream_run");
        // 设置头字段
        httpPost.setHeader("Authorization", "Bearer " + JWTSignature.getToken());
        httpPost.addHeader("content-type", "application/json; charset=UTF-8");
        // 设置内容信息
        JSONObject json = new JSONObject();
        json.put("workflow_id", workflowId);
        Map<String,Object> parameters = new HashMap<>();
        parameters.put("input", input);
        json.put("parameters", parameters);
        StringEntity params = new StringEntity(json.toString(),"UTF-8");
        params.setChunked(true);

        System.out.println(params);
        System.out.println(json.toString());
        httpPost.setEntity(params);

        new Thread(() -> {
            try {
                // 发送请求
                HttpResponse response = httpClient.execute(httpPost);
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Consts.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.equals("event: Done")) {
                        emitter.send(Result.success("结束"));
                        emitter.complete();
                        break;
                    }
                    // 增加异常处理
                    try {
                        if (line != null) {
                            emitter.send(line);
                            log.info("发送："+line);
                        }
                    } catch (IOException e) {
                        log.error("发送流数据时出错", e);
                        emitter.completeWithError(e);
                    }
                }
            } catch (IOException e) {
                log.error("执行 HTTP 请求时出错", e);
                emitter.completeWithError(e);
            }
        }).start();

        // 增加超时处理
        emitter.onTimeout(() -> {
            log.info("SseEmitter 超时");
            emitter.complete();
        });

        // 增加完成处理
        emitter.onCompletion(() -> log.info("SseEmitter 完成"));

        return emitter;
    }


    public static void deleteConversation() throws Exception {
        String CozeURL = "https://api.coze.cn/v1/conversation/message/delete";
        HttpPost httpPost = new HttpPost(CozeURL);
        // 设置头字段
        httpPost.setHeader("Authorization", "Bearer " + JWTSignature.getToken());
        httpPost.addHeader("content-type", "application/json");

        // 发送请求
        HttpClient httpclient = new DefaultHttpClient();
    }
}